package com.zee.wechat.framework.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;

import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;

/**
 * 定时任务工具类
 *
 * @author Zee
 * @version 1.0
 * @date 2020/9/1
 */
@Slf4j
@Configuration
public class JobHandlerUtil {
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private Map<String, ScheduledFuture> futureMap = new HashMap<>();

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        // 线程池数量
        executor.setPoolSize(Runtime.getRuntime().availableProcessors());
        //设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix("charge-task-Executor-");
        //用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //该方法用来设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }

    /**
     * 添加任务
     *
     * @param key         任务唯一key建议用id字段
     * @param runTime     任务执行时间
     * @param jobExecutor 任务执行器
     */
    public void addJob(String key, String runTime, JobExecutor jobExecutor) {
        Assert.notNull(jobExecutor, "jobExecutor不能为空");
        //设置定时任务
        ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(() -> {
            //执行具体任务
            jobExecutor.run(key);
            //执行完成后停止该任务
            this.stopJobs(new String[]{key});
        }, new CronTrigger(this.getCron(runTime)));
        //将scheduledFuture放入map容器中统一管理
        futureMap.put(key, scheduledFuture);
    }

    /**
     * 添加多任务
     *
     * @param keys        多个任务id建议用id加时间组合
     * @param runTimes    多个时间
     * @param jobExecutor 执行的任务
     */
    public void addJobs(String[] keys, String[] runTimes, JobExecutor jobExecutor) {
        for (int i = 0; i < keys.length; i++) {
            this.addJob(keys[i], runTimes[i], jobExecutor);
        }
    }

    /**
     * 停止任务
     *
     * @param keys key
     */
    public void stopJobs(String[] keys) {
        for (String key : keys) {
            if (futureMap.containsKey(key)) {
                futureMap.get(key).cancel(true);
                futureMap.remove(key);
            }
        }
    }

    /**
     * 获取定时表达式
     *
     * @param cronTime
     * @return 00 00 12 10 09 ?
     */
    private String getCron(String cronTime) {
        LocalDateTime dateTime = LocalDateTime.parse(cronTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return dateTime.format(DateTimeFormatter.ofPattern("ss mm HH dd MM ?"));
    }

    /**
     * 执行器interface
     */
    @FunctionalInterface
    public interface JobExecutor {
        /**
         * 任务执行
         *
         * @param key key
         */
        public void run(String key);
    }

}
